package pl.enigmatic.parser.string.pl.edu.enigma.time;

import java.util.HashSet;
import java.util.Set;

import pl.enigmatic.time.Duration;
import pl.enigmatic.util.Strings;
import pl.enigmatic.parser.string.Converter;


public class DurationConverter extends Converter<Duration> {

	private final TimeSpanConverter timespanConverter = new TimeSpanConverter();
	private final Set<String> forever = new HashSet<String>();
	private final Set<String> automatic = new HashSet<String>();

	public DurationConverter() {
		forever.add(Duration.Type.FOREVER.toString().toLowerCase());
		forever.add("always");
		forever.add("infinite");
		forever.add("inf");
		automatic.add(Duration.Type.AUTOMATIC.toString().toLowerCase());
		automatic.add("auto");
		automatic.add("adjust");
	}

	@Override
	public Duration convert(final String value) {
		if (Strings.nonEmpty(value)) {
			if (forever.contains(value.toLowerCase())) {
				return Duration.FOREVER;
			} else if (automatic.contains(value.toLowerCase())) {
				return Duration.AUTOMATIC;
			} else {
				return new Duration(timespanConverter.convert(value));
			}
		}
		return null;
	}

	@Override
	public String convertBack(final Duration value) {
		if (value.isForever()) {
			return Duration.Type.FOREVER.toString().toLowerCase();
		} else if (value.isAutomatic()) {
			return Duration.Type.AUTOMATIC.toString().toLowerCase();
		} else {
			return timespanConverter.convertBack(value.getTimeSpan());
		}
	}

}
